const util = require('../../../../../../utils/util.js');
const api = require('../../../../../../config/api.js');
const user = require('../../../../../../services/user.js');

const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 圈子id
    circleid: '',
    // 圈子信息
    interestData: { "feeSettingSwitch": 0, "refundSettings": 1, "experienceSwitch": 0, "experienceType": 0, "experienceDay": 0, "activityStartDate": "", "refundDay": 7, "isChargeTicket": 0, "isShowTicket": 1, "deleteTicketDialogShow": false, "deleteTicketIndex": "", "returnItemTypeIdentification": 0, "amountId":  "" },
    // 票种信息
    ticket: [],
    deleteTicketId: "",// 删除的票种id，多个用英文逗号隔开
    //文字描述
    descDialog: { "show": false, "type": 0 },
    // 可退款天数的数组
    refundDay: [1, 2, 3, 4, 5, 6, 7],
    // 是否为提交中
    isSubmit: true,
    // 票种是否可以提交
    verifyTicketSubmit: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var _this = this;
    var circleid = options.circleid;
    _this.setData({
      circleid: circleid
    })
    _this.loadAmountInfo();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var _this = this;
    _this.verifyTicketSubmit();
    _this.chechChargeTicket();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var _this = this;
    var feeSettingSwitch = _this.data.interestData.feeSettingSwitch;
    _this.setData({
      isUnload: true
    })
    if (feeSettingSwitch == 0) {
      // 返回上一页，如果没有选中收费，就进行保存
      _this.submit();
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 付费设置
   */
  feeSettingSwitchChange: function (e) {
    var _this = this;
    var feeSettingSwitch = _this.data.interestData.feeSettingSwitch != 1 ? 1 : 0;
    if (feeSettingSwitch == 1) {
      var ticket = _this.data.ticket;
      if (ticket.length <= 0) {
        _this.addTicket();
      }
      _this.setData({
        ["interestData.feeSettingSwitch"]: feeSettingSwitch
      })
    }else{
      // 关闭付费设置，需要校验当前圈子是否有用户加入
      var param = {};
      param.circleid = _this.data.circleid;
      util.post(api.Interest_getTicketBuyCountUrl, param).then(function (res2) {
        if (res2.code == 200) {
          var count = res2.result.obj;
          if(count <= 0){
            _this.setData({
              ["interestData.feeSettingSwitch"]: feeSettingSwitch
            })
          }else{
            util.showToast("已有用户购买了票种，不能关闭付费设置~", "none");
          }
        }
      })
    }
  },

  /**
   * 添加票种
   */
  addTicket: function () {
    var _this = this;
    var ticket = _this.data.ticket;
    if (ticket.length < 10) {
      // 初始化一个免费票种
      var data = {};
      data.id = "";
      data.name = "免费票种";
      data.price = "";// 原价，不填或填0为免费
      data.designatedType = 0;// 费用周期类型：0不限  1单次  2自定义
      data.designatedDays = 0;// 费用周期：0不限  1单次  其余的指定多少天就是多少
      data.numberPlaces = "";// 名额数量，不填为不限
      data.restrictionSetting = 1;//限购设置，必填的
      data.isOpenPreferentialSettings = 0;// 是否开启优惠设置：0否  1是
      data.preferentialSettings = "";// 票种类型：0打折优惠 1团购优惠 2橙贝互换
      data.preferentialdateStart = "";//优惠开始时间
      data.preferentialdateEnd = "";//优惠结束时间
      data.preferentialPrice = "";// 优惠金额，没有就不填
      data.orangeShell = "";//橙贝兑换价格
      data.isCommission = 0;// 是否开启分销：0否  1是
      data.commission = "";// 分销价格
      ticket.push(data);
      _this.setData({
        ticket: ticket
      })
      _this.verifyTicketSubmit();
    }
  },

  /**
   * 校验票种是否可以提交
   */
  verifyTicketSubmit: function () {
    var _this = this;
    var verifyTicketSubmit = true;
    var ticket = _this.data.ticket;
    for (var i = 0; i < ticket.length; i++) {
      if (ticket[i].name == null || ticket[i].name.trim().length <= 0) {
        verifyTicketSubmit = false
      }
    }
    _this.setData({
      verifyTicketSubmit: verifyTicketSubmit
    })
  },

  /**
   * 免费体验
   */
  experienceSwitchChange: function (e) {
    var _this = this;
    var experienceSwitch = _this.data.interestData.experienceSwitch != 1 ? 1 : 0;
    _this.setData({
      ["interestData.experienceSwitch"]: experienceSwitch
    })
    if (experienceSwitch == 1) {
      if (_this.data.interestData.experienceDay == 0) {
        _this.setData({
          ["interestData.experienceDay"]: 1,
          ["interestData.experienceType"]: 1
        })
      }
    }
  },

  /**
   * 体验周期点击事件
   */
  experienceDayClick: function (e) {
    var _this = this;
    var type = e.target.dataset.type;
    var experienceDay = '';
    if (type == 1) {
      experienceDay = 1;
    }
    if (type == 2) {
      experienceDay = 3;
    }
    _this.setData({
      ["interestData.experienceType"]: type,
      ["interestData.experienceDay"]: experienceDay
    })
  },

  /**
   * 自定义的体验周期的input点击事件
   */
  customExperienceInputClick: function (e) {
    var _this = this;
    var experienceDay = _this.data.experienceDay;
    if (experienceDay == 1 || experienceDay != 3) {
      experienceDay = '';
    }
    _this.setData({
      ["interestData.experienceType"]: 3,
      ["interestData.experienceDay"]: experienceDay
    })
  },

  /**
     * 自定义的体验周期的input输入事件
     */
  customExperienceInput: function (e) {
    var _this = this;
    _this.setData({
      ["interestData.experienceDay"]: e.detail.value
    })
  },

  /**
   * 退款设置
   */
  refundSettingsChange: function (e) {
    var _this = this;
    var refundSettings = _this.data.interestData.refundSettings;
    _this.setData({
      ["interestData.refundSettings"]: refundSettings != 1 ? 1 : 0
    })
  },

  /**
   * 退款天数value改变事件
   */
  refundDayChange: function (e) {
    var _this = this;
    _this.setData({
      ["interestData.refundDay"]: _this.data.refundDay[e.detail.value]
    })
  },
  /**
   * 文字描述：打开
   */
  descDialogShow: function (e) {
    var _this = this;
    var type = e.currentTarget.dataset.type;
    var descDialog = { "show": true, "type": type };
    _this.setData({
      descDialog: descDialog
    })
  },

  /**
   * 文字描述：关闭
   */
  descDialogClose: function (e) {
    var _this = this;
    var descDialog = { "show": false, "type": 0 };
    _this.setData({
      descDialog: descDialog
    })
  },

  /**
   * 跳转到圈子设置页面
   */
  navigateToCirCleopt: function () {
    wx.navigateBack({
      delta: 1
    })
  },

  /**
   * 票种隐藏或显示
   */
  isShowTicket: function () {
    var _this = this;
    _this.setData({
      ["interestData.isShowTicket"]: _this.data.interestData.isShowTicket == 1 ? 0 : 1
    })
  },

  /**
   * 添加或修改票种页面
   */
  navigateToDetails: function (e) {
    var _this = this;
    var ticketindex = e.currentTarget.dataset.ticketindex;
    var projectdateStart = _this.data.interestData.projectdateStart;
    var projectdateEnd = _this.data.interestData.projectdateEnd;
    if (ticketindex != null && String(ticketindex).length > 0){
      var id = _this.data.ticket[ticketindex].id;
      if (id != null && String(id).length > 0) {
        // 关闭付费设置，需要校验当前圈子是否有用户加入
        var param = {};
        param.amountDetailsId = id;
        util.post(api.Interest_getTicketBuyCountUrl, param).then(function (res2) {
          if (res2.code == 200) {
            var count = res2.result.obj;
            if (count <= 0) {
              _this.navigateToDetailsIndex(projectdateStart, projectdateEnd, ticketindex);
            } else {
              util.showToast("已有用户购买了票种，不能关闭付费设置~", "none");
            }
          }
        })
      } else {
        _this.navigateToDetailsIndex(projectdateStart, projectdateEnd, ticketindex);
      }
    } else {
      _this.navigateToDetailsIndex(projectdateStart, projectdateEnd, ticketindex);
    }
    
  },

  /**
   * 跳转到添加票种页面
   */
  navigateToDetailsIndex: function (projectdateStart, projectdateEnd, ticketindex){
    var _this = this;
    wx.navigateTo({
      url: "../registrationfee/details/index?projectdateStart=" + projectdateStart + "&projectdateEnd=" + projectdateEnd + "&ticketindex=" + ticketindex + "&oneTicket=" + JSON.stringify(_this.data.ticket[ticketindex])
    })
  },

  /**
   * 提交
   */
  submit: function () {
    var _this = this;
    _this.setData({
      "isSubmit": false
    })
    wx.showLoading({
      title: '提交中',
    })
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var deleteTicketId = _this.data.deleteTicketId;
        var param = {};
        param.openid = openid;
        param.circleid = _this.data.circleid;
        param.access_token = res.access_token;
        param.interestData = JSON.stringify(_this.data.interestData);
        param.ticket = JSON.stringify(_this.data.ticket);
        if (String(deleteTicketId).length > 0){
          param.deleteTicketId = deleteTicketId;
        }
        util.post(api.Interest_insertAmount, param).then(function (res2) {
          if (res2.code == 200) {
            var isUnload = _this.data.isUnload;
            if (!(isUnload == true)){
              wx.navigateBack({
                delta: 1
              })
            }
          }
          wx.hideLoading();
        })
      })
    }
  },

  /**
   * 校验是否可以有开启免费体验圈子的开关
   */
  chechChargeTicket: function () {
    var _this = this;
    var ticket = _this.data.ticket;
    var oldChargeTicket = _this.data.interestData.isChargeTicket;
    var isChargeTicket = 0;
    for (var i = 0; i < ticket.length; i++) {
      var price = parseInt(ticket[i].price);
      var preferentialPrice = parseInt(ticket[i].preferentialPrice);
      if (price > 0 || preferentialPrice > 0) {
        isChargeTicket = 1;
      }
    }
    if (oldChargeTicket == 0){
      _this.setData({
        ["interestData.refundSettings"]: 0
      })
    }
    _this.setData({
      ["interestData.isChargeTicket"]: isChargeTicket
    })
  },

  /**
   * 删除票种
   */
  deleteTicket: function(e){
    var _this = this;
    var ticketindex = e.currentTarget.dataset.ticketindex;
    var id = _this.data.ticket[ticketindex].id;
    if (id != null && String(id).length > 0) {
      // 关闭付费设置，需要校验当前圈子是否有用户加入
      var param = {};
      param.amountDetailsId = id;
      util.post(api.Interest_getTicketBuyCountUrl, param).then(function (res2) {
        if (res2.code == 200) {
          var count = res2.result.obj;
          if (count <= 0) {
            _this.deleteTicket2(ticketindex);
          } else {
            util.showToast("已有用户购买了票种，不能关闭付费设置~", "none");
          }
        }
      })
    }else{
      _this.deleteTicket2(ticketindex);
    }
  },

  deleteTicket2: function (ticketindex){
    var _this = this;
    _this.setData({
      ["interestData.deleteTicketDialogShow"]: true,
      ["interestData.deleteTicketIndex"]: ticketindex
    })
  },

  /**
   * 关闭删除票种弹窗
   */
  deleteTicketClose: function(){
    var _this = this;
    _this.setData({
      ["interestData.deleteTicketDialogShow"]: false,
      ["interestData.deleteTicketIndex"]: ''
    })
  },

  /**
   * 确认删除票种
   */
  deleteTicketConfirm: function(){
    var _this = this;
    var ticketindex = _this.data.interestData.deleteTicketIndex;
    var ticket = _this.data.ticket;
    var id = ticket[ticketindex].id;
    ticket.splice(ticketindex, 1);
    _this.setData({
      ticket: ticket
    })
    if(id != null && String(id).length > 0){
      var deleteTicketId = _this.data.deleteTicketId;
      if (String(deleteTicketId).length > 0){
        deleteTicketId = deleteTicketId + "," + id;
      }else{
        deleteTicketId = id;
      }
      _this.setData({
        deleteTicketId: deleteTicketId
      })
    }
    _this.deleteTicketClose();
  },

  /**
   * 加载圈子付费设置相关的信息
   */
  loadAmountInfo: function(){
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var param = {};
        param.openid = openid;
        param.circleid = _this.data.circleid;
        param.access_token = res.access_token;
        util.post(api.Interest_getAmountInfo, param).then(function (res2) {
          if (res2.code == 200) {
            var interestData = res2.result.interestData;
            var ticket = res2.result.ticket;
            _this.setData({
              interestData: interestData,
              ticket: ticket,
            })
            _this.getAmountScope();
          }
        })
      })
    }
  },

  /**
   * 获取圈子付费设置的价格范围
   */
  getAmountScope: function () {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var param = {};
        param.access_token = res.access_token;
        param.openid = openid;
        param.circleid = _this.data.circleid;
        util.post(api.Interest_GetAmountScopeApi, param).then(function (res) {
          if (res.code == 200) {
            var interestData = res.result.interestData;
            var projectdateStart = interestData.projectdateStart;
            var returnItemTypeIdentification = interestData.returnItemTypeIdentification;
            var activityStartDate = util.formatDate(new Date(projectdateStart.replace(/-/g, '/'))).replace(/-/g, '');
            _this.setData({
              ["interestData.projectdateStart"]: interestData.projectdateStart,
              ["interestData.projectdateEnd"]: interestData.projectdateEnd,
              ["interestData.activityStartDate"]: activityStartDate,
              ["interestData.returnItemTypeIdentification"]: returnItemTypeIdentification
            })
          }
        })
      })
    }
  }
})